//
//  UserManager.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/2.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "UserManager.h"
#import <LKDBHelper/LKDBHelper.h>
#import "YBApiManager+Friend.h"
#import "YBApiManager+Mine.h"
#import "YBApiManager+Chat.h"


#define User_My_Token @"User_My_UserID"

@implementation UserManager

+ (instancetype)shareManager {
    static UserManager *___usermanager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ___usermanager = [[UserManager alloc] init];
    });
    return ___usermanager;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSString *my_user_token = [[NSUserDefaults standardUserDefaults] objectForKey:User_My_Token];
        [self setMsgFontSize:[FileUtils readObjectFromUserDefaultWithKey:@"chat_msg_font_name"]];
        if (my_user_token) {
            NSString *fullPath = [[FileUtils documentsDirectory] stringByAppendingPathComponent:@"user.dat"];
            NSDictionary *dic  = [FileUtils readObjectFromPath:fullPath];
            self.me = [User mj_objectWithKeyValues:dic];
            self.me.token = my_user_token;
            NSLog(@"--------- db path = %@", [FileUtils documentsDirectory]);
            [self updateChatDBPath];
            [self getFriendListFromDB];
        }
        
        @weakify(self);
        [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_Friend_Info_Changed object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
                FriendItem *item = x.object;
                for (Address_groupItem *content in kUsermanager.friend_groupArray) {
                    for (FriendItem *friend  in content.friendArray) {
                        if ([friend.friend_id isEqualToString:item.friend_id] == YES) {
                            friend.nickname = item.nickname;
                            friend.username = item.username;
                            friend.avatar = item.avatar;
                            break;
                        }
                    }
                }
            for (FriendItem *friend  in self.friendArray) {
                if ([friend.friend_id isEqualToString:item.friend_id] == YES) {
                    friend.nickname = item.nickname;
                    friend.avatar = item.avatar;
                    friend.username = item.username;
                    break;
                }
            }
        }];
    }
    return self;
}
- (void)updateUserInfo {
    @weakify(self);
    [[[YBApiManager shareManager] getMyInfo] subscribeNext:^(id  _Nullable x) {
        NSDictionary *dataDic = [x objectForKey:@"data"];
        @strongify(self);
        [self saveUserWithInfo:dataDic];
    }];
}
- (void)updateChatDBPath {
    NSString *my_user_id = self.me.ID;
    if (my_user_id.isHaveStr) {
        [[FriendItem getUsingLKDBHelper]   setDBPath:[NSString stringWithFormat:@"%@/db/chat_%@.db",[FileUtils documentsDirectory], my_user_id]];
    }
}
- (void)getFriendListFromDB {
    self.friendArray = [FriendItem searchWithWhere:nil];
    self.friend_groupArray = [Address_groupItem searchWithWhere:nil];
}
- (void)saveUserWithInfo:(NSDictionary *)info {
    NSString *uid = [NSString kk_safeString:info[@"id"]];
    NSString *token = info[@"token"];
    if (token.isHaveStr) {
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:User_My_Token];
    }
    [FileUtils writeObject:info toDocumentPath:@"user.dat"];
    if (self.me && [self.me.ID isEqualToString:uid] == YES) {
        [self.me mj_setKeyValues:info];
    } else {
        self.me = [User mj_objectWithKeyValues:info];
        if (token.isHaveStr == NO) {
            self.me.token = [FileUtils readObjectFromUserDefaultWithKey:User_My_Token];
        }
    }
}
- (void)setMsgFontSize:(NSString *)msgFontSize {
    if (msgFontSize == nil) {
        msgFontSize = @"中";
    } else if (_msgFontSize == msgFontSize) {
        return;
    }
    _msgFontSize = msgFontSize;
    
    CGFloat size = 15;
    if ([msgFontSize isEqualToString:@"小"] == YES) {
        size = 12;
    } else if ([msgFontSize isEqualToString:@"大"] == YES) {
        size = 18;
    }
    [FileUtils writeObject:msgFontSize toUserDefaultWithKey:@"chat_msg_font_name"];
    _msgFont = [UIFont systemFontOfSize:size];
}
- (void)clean {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_My_Token];
    _me = nil;
    [self.friendArray removeAllObjects];
    self.currentSession = nil;
}

- (BOOL)isLogin {
    return self.me && self.me.token.isHaveStr;
}


#pragma mark - friend
- (void)updateFriendList {
    @weakify(self);
    [[YBApiManager.shareManager getFriendList] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        NSArray *dataArr = [x objectForKey:@"data"];
        self.friendArray = [FriendItem mj_objectArrayWithKeyValuesArray:dataArr];
        [FriendItem insertArrayByAsyncToDB:self.friendArray];
        [[NSNotificationCenter defaultCenter] postNotificationName:notificaiton_FriendList_updated object:nil];
    } error:^(NSError * _Nullable error) {
    }];
    [self updateFriend_groupList];
}
- (void)updateFriend_groupList {
    @weakify(self);
    [[YBApiManager.shareManager getFriend_groupList] subscribeNext:^(id  _Nullable x) {
        NSMutableArray *dataArr = [x objectForKey:@"data"];
        @strongify(self);
        NSMutableArray *groups = [NSMutableArray array];
        Address_groupItem *blacklist = nil;
        for (NSDictionary *dic in dataArr) {
            Address_groupItem *item = [Address_groupItem mj_objectWithKeyValues:dic];
            NSMutableString *ids = [NSMutableString string];
            NSMutableArray *friends = item.friendArray; //[FriendItem mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"sort"]];
            for (FriendItem *obj in friends) {
                [ids appendFormat:@"%@,", obj.friend_id];
            }
            item.friends = ids;
//            item.friendArray = friends;
            if ([item.name isEqualToString:@"黑名单"] == YES) {
                blacklist = item;
            } else {
                [groups addObject:item];
            }
        }
        if (blacklist) {
            [groups addObject:blacklist];
        }
        
        [Address_groupItem insertArrayByAsyncToDB:groups];
        self.friend_groupArray = groups;
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_Friend_groupList_updated object:nil];

        
    } error:^(NSError * _Nullable error) {
        
    }];
}

- (void)updateGroupChatList {
    [[YBApiManager.shareManager getGroupChatList] subscribeNext:^(id  _Nullable x) {
        NSArray *dataArr = [x objectForKey:@"data"];
        self.groupChatArray = [GroupItem mj_objectArrayWithKeyValuesArray:dataArr];
        [GroupItem insertArrayByAsyncToDB:self.groupChatArray];
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_GroupChatList_updated object:nil];
    } error:^(NSError * _Nullable error) {
        
    }];
}

- (void)getFriendWithUserId:(NSString *)uid groupId:(NSString *)groupId callbackBlock:(void(^)(FriendItem *friendItem))complete {
    
    FriendItem *item = nil;
    for (FriendItem *obj in self.friendArray) {
        if ([obj.group_id isEqualToString:groupId] == YES) {
            item = obj;
            break;
        }
    }
    
    if (item && complete) {
        complete(item);
        return;
    }
    if (item == nil && uid.integerValue != 0) {
        
        item = [FriendItem searchSingleWithWhere:@{@"friend_id": uid} orderBy:nil];
        if (item && complete) {
            complete(item);
            return;
        }
        
        [[YBApiManager.shareManager searchUserWithUid:uid] subscribeNext:^(id  _Nullable x) {
            NSDictionary *dataDic = [x objectForKey:@"data"];
            FriendItem *newItem = [FriendItem mj_objectWithKeyValues:dataDic];
            [newItem updateToDB];
            if (complete) {
                complete(newItem);
            }
        }];
    }
}

- (void)getGroupWithGroupId:(NSString *)groupId callbackBlock:(void(^)(GroupItem *item))complete {
    [self getGroupInfoWithGroupId:groupId needUpdate:NO callbackBlock:complete];
}
- (void)getGroupInfoWithGroupId:(NSString *)groupId needUpdate:(BOOL)update callbackBlock:(void(^)(GroupItem *item))complete {

    if (update == NO) {
        GroupItem *group = [GroupItem searchSingleWithWhere:@{@"group_id": groupId} orderBy:nil];
        if (group) {
            complete(group);
            return;
        }
    }
    
    [[YBApiManager.shareManager groupInfoWithGroupId:groupId] subscribeNext:^(id  _Nullable x) {
        NSDictionary *dataDic = [x objectForKey:@"data"];
        GroupItem *group = [GroupItem mj_objectWithKeyValues:dataDic];
        [group updateToDB];
        complete(group);
    }];
}

@end
